package com.training.java.redbox.struts.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.training.java.redbox.struts.domain.Customer;
import com.training.java.redbox.struts.domain.CustomerDAO;
import com.training.java.redbox.struts.domain.CustomerDaoJdbcImpl;
import com.training.java.redbox.struts.domain.CustomerService;
import com.training.java.redbox.struts.domain.DAOException;
import com.training.java.redbox.struts.domain.ServiceException;


public class LoginFormAction extends Action {
	@Override
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception

	{
		System.out.println("i am in loginformaction");
		
		ServletContext servletContext = servlet.getServletContext();
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		CustomerService service = context.getBean(CustomerService.class);

		//CustomerDAO customerDao = new CustomerDaoJdbcImpl();
		
		LoginForm loginForm =  (LoginForm) form; 
		
		String username = loginForm.getUsername();
		System.out.println("username= "+ username);
		String password = loginForm.getPassword();
		System.out.println("password: " + password );
		Customer customer= new Customer();

		try {
			customer = service.login(username, password);

			if (customer == null) 
			{
				request.setAttribute("username", username);
				//request.setAttribute(	"ErrorMessage","Please correct the following errors and try again: The username or password is incorrect.");
				ActionErrors errors= new ActionErrors();
				errors.add("InvalidLogin", new ActionMessage("login.invalid"));
				saveErrors(request, errors);
				return mapping.findForward("login");

			} else {
				HttpSession session = request.getSession();
				session.setAttribute("Customer", customer);

				System.out.println("customerid= " + customer.getCustomerId());

				//return mapping.findForward("listMovies");
				return mapping.findForward("list");
			}

		} catch (ServiceException e) {
			e.printStackTrace();
			return mapping.findForward("list");
		}
		
		
	}
}
